'''
Created on 12/03/2010

@author: igonzalez
'''

from django.http import HttpResponse
from format.utils import  getResponseFormat, generateResponse

from os import path
from xml.dom import minidom
import copy
import urllib

from GIC.Channels.Items.VideoItem import *
from GIC.Channels.GenericChannel import *

PAGE = 0
N_ELEMS = 20

class CvideoLoader(object):
    '''
    classdocs
    '''

    def __init__(self):
        self.array = []
        self.count = 0   
        
        #this function generates a geonode array using the xml that openadaptor has generated
    def generate_Array(self, channel,category):
        channel = channel.lower()
        category = category.lower()
        direccion = self.getPath()
        xml = str(direccion) + "/agregator_files/xmlConf/" + channel + "_" + category + ".xml"
        xmldoc = minidom.parse(xml)
        son = xmldoc.firstChild
        self.count = int(son.getAttribute('size'))
        videoList = son.getElementsByTagName('video')
        i = 0
        while(i < self.count):
            tempVideo = VideoItem()
            tempVideo.id = videoList[i].getAttribute('id')
            id = videoList[i].getAttribute('id')
            title = videoList[i].getElementsByTagName('title')
            if (len(title) > 0):
                if (title[0].firstChild != None):
                    tempVideo.name = title[0].firstChild.nodeValue
            author = videoList[i].getElementsByTagName('author')
            if (len(author) > 0): 
                authorName = author[0].getElementsByTagName('name')
                if (len(authorName) > 0):
                    if (authorName[0].firstChild != None):
                        tempVideo.uploader = authorName[0].firstChild.nodeValue
            recorded = videoList[i].getElementsByTagName('recorded')
            if (len(recorded) > 0):
                if (recorded[0].firstChild != None):
                    tempVideo.since = recorded[0].firstChild.nodeValue
            content = videoList[i].getElementsByTagName('content')
            if (len(content) > 0):
                if (content[0].firstChild != None):    
                    tempVideo.description = str(content[0].firstChild.nodeValue)
            links = videoList[i].getElementsByTagName('links')
            if (len(links) > 0):
                urlList = links[0].getElementsByTagName('link')
                if (len(urlList) > 0):
                    if (len(urlList) > 1):
                        tempVideo.external_info['video_url'] = urlList[1].firstChild.nodeValue     
                    else: 
                        tempVideo.external_info['video_url'] = str(urlList[0].firstChild.nodeValue).replace('&feature=youtube_gdata', '')           
            thumbnails = videoList[i].getElementsByTagName('thumbnails')
            if (len(thumbnails) > 0): 
                thumbnail = thumbnails[0].getElementsByTagName('thumbnail')
                if (len(thumbnail) > 0):
                    if (thumbnail[0].firstChild != None):    
                        tempVideo.external_info['video_thumbnail'] = thumbnail[0].firstChild.nodeValue
            tempVideo.icon = "/social/layer/" + channel + "/icon"            
            self.array.append(copy.deepcopy(tempVideo))
            i = i + 1             
        return self.array  
    
          #this function manages the geonode generation with httpresponse only useful for petitions without client
    def generate_all(self, channel,category, request):   
        format = getResponseFormat (request)   
        channel = str(channel.lower())
        category = str(category.lower())  
        #calls the generate array function             
        self.generate_Array(channel,category)
        #makes the pagination and returns a HttpResponse with the geonodes using a template
        f, t, page, elems = self.get_limits(request)
        array2 = copy.deepcopy(self.array)
        self.array = self.select_limits (f, t, array2)
        data = {'code'    : '200',
                'id_type' : str(category) + 's',
                'videos'  : self.array,
                'page'    : page,
                'elems'   : len(self.array),
                'type'    : str(category) + "_list" }
        return generateResponse(format, data, "video/list") 
    
    def select_limits(self, from_limit, to_limit, nodes):
        return nodes[from_limit:to_limit]        
            
    def get_limits(self, request):
        if "page" in request.REQUEST:
            page = request.REQUEST["page"]
        else:
            page = None
        if "elems" in request.REQUEST:
            elems = request.REQUEST["elems"]
        else:
            elems = None
        try:
            page = int(page) - 1
            if page < 0:
                raise ValueError()
        except:
            page = PAGE
        try:
            elems = int(elems)
            if elems < 0:
                raise ValueError()
        except:
            elems=N_ELEMS
        f = elems * page
        t = f + elems
        return (f, t, page+1, elems)
               
    def getPath(self):
        direccion2 = path.dirname(path.abspath(__file__))
        return direccion2